#! /bin/bash

# this script file path.
cd `echo ${0%/*}`
THIS_FILE_PATH=`pwd`
THIS_FILE_PATH=$THIS_FILE_PATH/

ACTION="build"
if [ $# -gt 0 ]; then
    ACTION=$1
fi

ROBOTAXI_MSG_PATH=$THIS_FILE_PATH/../

function msg2idl() {
    MSG2IDLPY=/opt/ros/foxy/lib/rosidl_adapter/msg2idl.py
    if [ ! -f "$MSG2IDLPY" ]; then
        echo "$MSG2IDLPY does not exist."
        return 0
    fi
    pushd $ROBOTAXI_MSG_PATH > /dev/null
    find -type d \( -name 'map_msgs' -prune \) -o -type f -name '*.msg' -exec python3 ${MSG2IDLPY} {} \;
    popd > /dev/null
}

function idl_repeat_fix() {
    pushd $ROBOTAXI_MSG_PATH/generated/idl > /dev/null
    PathPoint_idl_file="PathPoint.idl"
    conten1="#ifndef __planning_msgs__msg__PathPoint__idl"
    conten2="#define __planning_msgs__msg__PathPoint__idl"
    conten3="#endif"
    sed -i '5i\'"$conten1" "$PathPoint_idl_file"
    sed -i '6i\'"$conten2" "$PathPoint_idl_file"
    echo -e "$conten3" >> "$PathPoint_idl_file"
    popd > /dev/null
}

function idl2cpp() {
    type fastddsgen > /dev/null 2>&1 || echo "fastddsgen command not found, exit."
    type fastddsgen > /dev/null 2>&1 || return 0

    pushd $ROBOTAXI_MSG_PATH > /dev/null
    mkdir -p $ROBOTAXI_MSG_PATH/generated/idl
    mkdir -p $ROBOTAXI_MSG_PATH/generated/cpp
    mkdir -p $ROBOTAXI_MSG_PATH/generated/inc
    mkdir -p $ROBOTAXI_MSG_PATH/generated/src
    find $ROBOTAXI_MSG_PATH -type d \( -name 'generated' -prune \) -o -type f -name '*.idl' -exec cp {} $ROBOTAXI_MSG_PATH/generated/idl \;
    for idl_file in $ROBOTAXI_MSG_PATH/generated/idl/*.idl
    do
        include_files=$( grep -oP '#include "\K[^"]+' "$idl_file" )
        sed -i -E 's|#include "[^/]+/[^/]+/(.*)\.idl"|#include "\1.idl"|' "$idl_file"
    done
    idl_repeat_fix
    popd > /dev/null

    pushd $ROBOTAXI_MSG_PATH/generated/idl > /dev/null
    fastddsgen -cs *.idl -d $ROBOTAXI_MSG_PATH/generated/cpp
    [[ $? -eq 0 ]] || exit 1
    mv $ROBOTAXI_MSG_PATH/generated/cpp/*.h $ROBOTAXI_MSG_PATH/generated/inc
    mv $ROBOTAXI_MSG_PATH/generated/cpp/*.cxx $ROBOTAXI_MSG_PATH/generated/src
    popd > /dev/null
}

function build() {
    msg2idl
    [[ $? -eq 0 ]] || exit 1
    idl2cpp
    [[ $? -eq 0 ]] || exit 1
    echo "done..."
}

function help() {
    pass
}

case ${ACTION} in
    "build") build ;;
    "help") help ;;
    *) help ;;
esac
